use std::process::{Command, Stdio};
use regex::Regex;

pub fn is_process_running(exe_name: &str) -> bool {
    let output = Command::new("tasklist")
    .output()
    .expect("Failed to execute tasklist");

    if !output.status.success() {
        eprintln!("Failed to get process list");
        return false;
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let re = Regex::new(&format!(r"(?i){}\.exe", exe_name)).unwrap();

// 检查输出中是否存在指定的可执行文件名
    stdout.lines().any(|line| re.is_match(line))
}

pub fn terminate_process(exe_name: &str) {
    let output = Command::new("taskkill")
        .args(&["/F", "/IM", &format!("{}.exe", exe_name)])
        .output()
        .expect("Failed to execute taskkill");

    if output.status.success() {
        println!("Successfully terminated {}", exe_name);
    } else {
        eprintln!("Failed to terminate {}: {}", exe_name, String::from_utf8_lossy(&output.stderr));
    }
}

pub fn start_process(exe_path: &str) {
    match Command::new(exe_path)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
    {
    Ok(_) => println!("Process started successfully."),
    Err(e) => eprintln!("Failed to start process: {}", e),
    }
}

pub fn restart_or_start_process(exe_name: &str, exe_path: &str) {
    if is_process_running(exe_name) {
        println!("{} is running. Terminating and restarting...", exe_name);
        terminate_process(exe_name);
    } else {
        println!("{} is not running. Starting it now...", exe_name);
    }
    start_process(exe_path);
}
